using UnityEngine;
using System.Collections;

public class ExperienceBar : MonoBehaviour
{
	public UISprite experienceBarSprite;
	public UILabel experienceLabel;
	float maxLength;
	int mExp;
	
	void Awake ()
	{	
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_ROLE_LEVEL_UP_PSH, LevelUp);
		//BindManage.getInstance ().BindProp (ModelLocator.getInstance ().scene.Role, "Level", this, "LevelUp");
	}

	// Use this for initialization
	void Start ()
	{
		if (experienceBarSprite == null) {
			experienceBarSprite = transform.GetComponentInChildren<UISprite> ();
		}
		
		if (experienceLabel == null) {
			experienceLabel = transform.GetComponentInChildren<UILabel> ();
		}
		
		//TODO,Get from somewherez
		PlayerData.Instance().maxExp = 200;
		
		maxLength = experienceBarSprite.transform.localScale.x;
		
		Refresh ();
		
		BindManage.getInstance ().BindProp (ModelLocator.getInstance ().scene.Role, "Exp", this, "BindExp");
	}
	
	public void LevelUp (System.Object sender, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		PlayerData.Instance().maxExp = byteArray.readInt();
		
		EffectManagement.GetInstance().PlayEffect(PlayerData.Instance().MainRoleInstance,"LevelUp");
		
		Refresh ();
	}
	
	public void BindExp (object property, object propertyValue)
	{
		
		//经验显示//
		string expStr = propertyValue.ToString ();
		if (expStr == "")
			mExp = 0;
		else
			mExp = int.Parse (expStr);
		
		Refresh ();
	}
	
	void Refresh ()
	{
		if (mExp >= PlayerData.Instance().maxExp) {
			mExp -= PlayerData.Instance().maxExp;
		}
		
		Vector3 scale = experienceBarSprite.transform.localScale;
		scale.x = mExp / (float)PlayerData.Instance().maxExp * maxLength;
		
		if(scale.x == 0f){
			scale.x = 0.001f;
		}
		
		experienceBarSprite.transform.localScale = scale;
		
		int rate = (int)(mExp / (float)PlayerData.Instance().maxExp * 100);
		string expRate = rate.ToString () + "%" + "(" + mExp.ToString () + "/" + PlayerData.Instance().maxExp.ToString () + ")";
		experienceLabel.text = expRate;
	}
	void OnDestroy ()
	{
		BindManage.getInstance ().UnbindProp (ModelLocator.getInstance ().scene.Role, "Exp");
	}
	
	
	void OnGUI ()
	{
		if (GUI.Button (new Rect (500, 500, 100, 50), "Add exprience")) {
			ByteArrayEx byteArray = new ByteArrayEx ();
			
			byteArray.writeInt ((int)SystemMsgFlag.NetMessageCS.NM_CS_ROLE_ADD_EXPERIENCE);
			byteArray.writeInt (401);
			
			MySocket.getInstance ().Async_Send (byteArray.byteArray);
			
			Refresh ();
		}
	}
}
